// src/userStore.js
import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    users: JSON.parse(localStorage.getItem('users')) || [],
    currentUser: null
  }),
  actions: {
    registerUser(user) {
      // 检查用户名是否已存在
      const existingUser = this.users.find(u => u.username === user.username);
      if (existingUser) {
        return false; // 用户名已存在
      }
      
      this.users.push(user);
      localStorage.setItem('users', JSON.stringify(this.users));
      return true; // 注册成功
    },
    loginUser(username, password) {
      const user = this.users.find(u => u.username === username && u.password === password);
      if (user) {
        this.currentUser = user;
        localStorage.setItem('currentUser', JSON.stringify(user));
        return true;
      }
      return false;
    },
    logoutUser() {
      this.currentUser = null;
      localStorage.removeItem('currentUser');
    },
    loadCurrentUser() {
      const user = JSON.parse(localStorage.getItem('currentUser'));
      if (user) {
        this.currentUser = user;
      }
    }
  }
});